export default class Snake {
    head: HTMLElement;
    bodies: HTMLCollection;
    snake: HTMLElement;
    constructor() {
        this.snake = document.getElementById('snake')
        this.head = document.querySelector('#snake>div')
        this.bodies = this.snake.getElementsByTagName('div')
    }

    //获取蛇头的坐标
    get headX() {
        return this.head.offsetLeft
    }
    get headY() {
        return this.head.offsetTop
    }

    //设置蛇头的坐标
    set headX(val: number) {
        if(this.headX === val){
            return
        }
        //X的合法范围 0~290
        if(val <0 || val>290){
            //蛇撞墙，左右
            throw new Error('蛇撞墙')
        }
        this.moveBody()
        this.head.style.left = val + 'px'
        
    }
    set headY(val: number) {
        if(this.headY === val){
            return
        }
        //Y的合法范围 0~290
        if(val <0 || val>290){
            //蛇撞墙，左右
            throw new Error('蛇撞墙')
        }
        this.moveBody()
        this.head.style.top = val + 'px'    
        
    }

    //增加身体的方法
    addBody() {
        this.snake.insertAdjacentHTML('beforeend', '<div></div>')
    }

    //移动身体方法
    moveBody() {
        for(let i = this.bodies.length-1;i>0;i--){
            //获取前面身体位置
            let x = (this.bodies[i-1] as HTMLElement).offsetLeft;
            let y = (this.bodies[i-1] as HTMLElement).offsetTop;
            (this.bodies[i] as HTMLElement).style.left = x + 'px';
            (this.bodies[i] as HTMLElement).style.top = y + 'px';
        }
    }

    
}